package errors

import (
	"fmt"
	"github.com/hashicorp/hcl/v2"
)

const (
	UnsupportedAttribute = "Unsupported attribute"
)

func Filter(diags hcl.Diagnostics, filter func(*hcl.Diagnostic) bool) hcl.Diagnostics {
	var result hcl.Diagnostics
	for _, dig := range diags {
		if filter(dig) {
			result = append(result, dig)
		}
	}
	return result
}

func Not(fn func(*hcl.Diagnostic) bool) func(*hcl.Diagnostic) bool {
	return func(dig *hcl.Diagnostic) bool {
		return !fn(dig)
	}
}

func IsDependsOnUnSupported(dig *hcl.Diagnostic) bool {
	return dig.Summary == "Unsupported argument" && dig.Detail == "An argument named \"depends_on\" is not expected here."
}

func IsUnsupportedAttribute(dig *hcl.Diagnostic) bool {
	return dig.Summary == UnsupportedAttribute
}

func NotOnlyUnsupportedAttribute(diags hcl.Diagnostics) bool {
	return Filter(diags, Not(IsUnsupportedAttribute)).HasErrors()
}

func NewDiagnostics(summary, format string, args ...string) hcl.Diagnostics {
	return Diagnostics(summary, fmt.Errorf(format, args))
}

func Diagnostics(title string, err error) hcl.Diagnostics {
	return hcl.Diagnostics{
		&hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  title,
			Detail:   err.Error(),
		},
	}
}

func SubjectDiagnostics(subject *hcl.Range, summary string, err error) hcl.Diagnostics {
	return hcl.Diagnostics{
		&hcl.Diagnostic{
			Subject:  subject,
			Severity: hcl.DiagError,
			Summary:  summary,
			Detail:   err.Error(),
		},
	}
}
